<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>沟通记录 - 售后管理系统</title>
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }

        body {
            font-family: 'Microsoft YaHei', Arial, sans-serif;
            background-color: #f5f5f5;
        }

        .header {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            padding: 20px;
            display: flex;
            justify-content: space-between;
            align-items: center;
        }

        .header h1 {
            font-size: 24px;
        }

        .back-btn {
            background: rgba(255, 255, 255, 0.2);
            border: 1px solid rgba(255, 255, 255, 0.3);
            color: white;
            padding: 8px 16px;
            border-radius: 5px;
            cursor: pointer;
            text-decoration: none;
        }

        .container {
            max-width: 800px;
            margin: 0 auto;
            padding: 20px;
        }

        .chat-container {
            background: white;
            border-radius: 10px;
            box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
            height: 600px;
            display: flex;
            flex-direction: column;
        }

        .chat-header {
            padding: 20px;
            border-bottom: 1px solid #e1e5e9;
            background: #f8f9fa;
            border-radius: 10px 10px 0 0;
        }

        .chat-title {
            font-size: 18px;
            font-weight: 600;
            color: #333;
            margin-bottom: 5px;
        }

        .chat-subtitle {
            font-size: 14px;
            color: #666;
        }

        .chat-messages {
            flex: 1;
            overflow-y: auto;
            padding: 20px;
        }

        .message {
            margin-bottom: 20px;
            display: flex;
            align-items: flex-start;
        }

        .message.sent {
            justify-content: flex-end;
        }

        .message.received {
            justify-content: flex-start;
        }

        .message-avatar {
            width: 40px;
            height: 40px;
            border-radius: 50%;
            display: flex;
            align-items: center;
            justify-content: center;
            font-weight: bold;
            color: white;
            font-size: 14px;
            margin: 0 10px;
        }

        .message.sent .message-avatar {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
        }

        .message.received .message-avatar {
            background: #28a745;
        }

        .message-content {
            max-width: 70%;
            padding: 12px 16px;
            border-radius: 18px;
            position: relative;
        }

        .message.sent .message-content {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            border-bottom-right-radius: 4px;
        }

        .message.received .message-content {
            background: #f1f3f4;
            color: #333;
            border-bottom-left-radius: 4px;
        }

        .message-text {
            line-height: 1.4;
            margin-bottom: 5px;
        }

        .message-time {
            font-size: 11px;
            opacity: 0.7;
        }

        .message.sent .message-time {
            text-align: right;
        }

        .chat-input {
            padding: 20px;
            border-top: 1px solid #e1e5e9;
            background: #f8f9fa;
            border-radius: 0 0 10px 10px;
        }

        .input-container {
            display: flex;
            gap: 10px;
            align-items: flex-end;
        }

        .message-input {
            flex: 1;
            padding: 12px 16px;
            border: 2px solid #e1e5e9;
            border-radius: 20px;
            font-size: 14px;
            resize: none;
            min-height: 44px;
            max-height: 120px;
            font-family: inherit;
        }

        .message-input:focus {
            outline: none;
            border-color: #667eea;
        }

        .send-btn {
            padding: 12px 20px;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            border: none;
            border-radius: 20px;
            cursor: pointer;
            font-size: 14px;
            font-weight: 500;
            transition: transform 0.2s ease;
        }

        .send-btn:hover {
            transform: translateY(-1px);
        }

        .send-btn:disabled {
            opacity: 0.6;
            cursor: not-allowed;
            transform: none;
        }

        .loading {
            text-align: center;
            padding: 40px;
        }

        .spinner {
            border: 2px solid #f3f3f3;
            border-top: 2px solid #667eea;
            border-radius: 50%;
            width: 30px;
            height: 30px;
            animation: spin 1s linear infinite;
            display: inline-block;
        }

        @keyframes spin {
            0% { transform: rotate(0deg); }
            100% { transform: rotate(360deg); }
        }

        .error-message {
            color: #e74c3c;
            text-align: center;
            padding: 20px;
            font-size: 16px;
        }

        .empty-state {
            text-align: center;
            padding: 40px;
            color: #666;
        }

        .empty-state h3 {
            margin-bottom: 10px;
            color: #333;
        }

        .system-message {
            text-align: center;
            margin: 20px 0;
        }

        .system-message .message-content {
            background: #fff3cd;
            color: #856404;
            border-radius: 10px;
            padding: 8px 16px;
            font-size: 12px;
            max-width: 300px;
            margin: 0 auto;
        }
    </style>
</head>
<body>
    <div class="header">
        <h1>沟通记录</h1>
        <a href="/after_sale_system/page/consumer/applicationList" class="back-btn">返回列表</a>
    </div>

    <div class="container">
        <div id="chatContainer">
            <div class="loading">
                <div class="spinner"></div>
                <p>加载中...</p>
            </div>
        </div>
    </div>

    <script>
        let applicationId = null;
        let currentUser = null;

        // 获取URL参数
        function getUrlParameter(name) {
            name = name.replace(/[\[]/, '\\[').replace(/[\]]/, '\\]');
            var regex = new RegExp('[\\?&]' + name + '=([^&#]*)');
            var results = regex.exec(location.search);
            return results === null ? '' : decodeURIComponent(results[1].replace(/\+/g, ' '));
        }

        // 页面加载时初始化
        window.addEventListener('load', function() {
            applicationId = getUrlParameter('id');
            if (applicationId) {
                loadApplicationInfo();
                loadMessages();
                loadCurrentUser();
            } else {
                showError('缺少申请ID参数');
            }
        });

        // 加载申请信息
        function loadApplicationInfo() {
            fetch(`/after_sale_system/api/afterSale/${applicationId}`)
                .then(response => response.json())
                .then(data => {
                    if (data.success) {
                        displayChatHeader(data.data);
                    }
                })
                .catch(error => {
                    console.error('获取申请信息失败:', error);
                });
        }

        // 加载当前用户信息
        function loadCurrentUser() {
            fetch('/after_sale_system/api/user/info')
                .then(response => response.json())
                .then(data => {
                    if (data.success) {
                        currentUser = data.data;
                    }
                })
                .catch(error => {
                    console.error('获取用户信息失败:', error);
                });
        }

        // 显示聊天头部
        function displayChatHeader(application) {
            const container = document.getElementById('chatContainer');
            container.innerHTML = `
                <div class="chat-container">
                    <div class="chat-header">
                        <div class="chat-title">申请编号: ${application.id}</div>
                        <div class="chat-subtitle">${getTypeText(application.afterSaleType)} - ${getStatusText(application.status)}</div>
                    </div>
                    <div class="chat-messages" id="messageContainer">
                        <div class="loading">
                            <div class="spinner"></div>
                            <p>加载消息中...</p>
                        </div>
                    </div>
                    <div class="chat-input">
                        <div class="input-container">
                            <textarea 
                                class="message-input" 
                                id="messageInput" 
                                placeholder="输入消息..."
                                rows="1"
                            ></textarea>
                            <button class="send-btn" id="sendBtn" onclick="sendMessage()">发送</button>
                        </div>
                    </div>
                </div>
            `;

            // 设置输入框自动调整高度
            const messageInput = document.getElementById('messageInput');
            messageInput.addEventListener('input', function() {
                this.style.height = 'auto';
                this.style.height = Math.min(this.scrollHeight, 120) + 'px';
            });

            // 回车发送消息
            messageInput.addEventListener('keypress', function(e) {
                if (e.key === 'Enter' && !e.shiftKey) {
                    e.preventDefault();
                    sendMessage();
                }
            });
        }

        // 加载消息
        function loadMessages() {
            fetch(`/after_sale_system/api/communication/?applicationId=${applicationId}`)
                .then(response => response.json())
                .then(data => {
                    if (data.success) {
                        displayMessages(data.data);
                    } else {
                        showError('获取消息失败: ' + data.message);
                    }
                })
                .catch(error => {
                    console.error('获取消息失败:', error);
                    showError('获取消息失败，请稍后重试');
                });
        }

        // 显示消息
        function displayMessages(messages) {
            const container = document.getElementById('messageContainer');
            
            if (!messages || messages.length === 0) {
                container.innerHTML = `
                    <div class="empty-state">
                        <h3>暂无沟通记录</h3>
                        <p>开始发送消息与客服沟通</p>
                    </div>
                `;
                return;
            }

            container.innerHTML = messages.map(message => `
                <div class="message ${message.senderType === 'CONSUMER' ? 'sent' : 'received'}">
                    <div class="message-avatar">
                        ${message.senderType === 'CONSUMER' ? '我' : '客'}
                    </div>
                    <div class="message-content">
                        <div class="message-text">${message.content}</div>
                        <div class="message-time">${formatDate(message.sendTime)}</div>
                    </div>
                </div>
            `).join('');

            // 滚动到底部
            container.scrollTop = container.scrollHeight;
        }

        // 发送消息
        function sendMessage() {
            const messageInput = document.getElementById('messageInput');
            const sendBtn = document.getElementById('sendBtn');
            const content = messageInput.value.trim();

            if (!content) return;

            // 禁用发送按钮
            sendBtn.disabled = true;
            sendBtn.textContent = '发送中...';

            const messageData = {
                applicationId: applicationId,
                content: content,
                senderType: 'CONSUMER'
            };

            fetch('/after_sale_system/api/communication/', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify(messageData)
            })
            .then(response => response.json())
            .then(data => {
                sendBtn.disabled = false;
                sendBtn.textContent = '发送';
                messageInput.value = '';
                messageInput.style.height = 'auto';

                if (data.success) {
                    // 重新加载消息
                    loadMessages();
                } else {
                    alert('发送失败: ' + data.message);
                }
            })
            .catch(error => {
                sendBtn.disabled = false;
                sendBtn.textContent = '发送';
                console.error('发送消息失败:', error);
                alert('发送失败，请稍后重试');
            });
        }

        // 获取类型文本
        function getTypeText(type) {
            const typeMap = {
                'RETURN': '退货',
                'EXCHANGE': '换货',
                'REPAIR': '维修'
            };
            return typeMap[type] || type;
        }

        // 获取状态文本
        function getStatusText(status) {
            const statusMap = {
                'PENDING_AUDIT': '待审核',
                'PROCESSING': '处理中',
                'COMPLETED': '已完成',
                'REJECTED': '已拒绝'
            };
            return statusMap[status] || status;
        }

        // 格式化日期
        function formatDate(dateString) {
            if (!dateString) return '';
            const date = new Date(dateString);
            return date.toLocaleString('zh-CN');
        }

        function showError(message) {
            document.getElementById('chatContainer').innerHTML = `
                <div class="error-message">${message}</div>
            `;
        }
    </script>
</body>
</html> 